<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="健康名称" prop="healthName">
              <el-input v-model="queryParams.healthName" placeholder="请输入健康名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddOne" v-hasPermi="['system:healthClassification:add']">新增一级分类</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:healthClassification:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:healthClassification:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:healthClassification:export']">导出</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- <el-table v-loading="loading" :data="healthClassificationList" @selection-change="handleSelectionChange"> -->
        <el-table
        ref="deptTableRef"
        v-loading="loading"
        :data="healthClassificationList"
        row-key="healthId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpandAll"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="id" align="center" prop="healthId" v-if="true" width="50"/> -->
        <el-table-column label="健康名称" align="center" prop="healthName" />
        <el-table-column label="健康类别编码" align="center" prop="healthCategory" />
        <el-table-column label="健康图标" align="center" prop="healthPathIcon" >
         <template #default="scope">
            <image-preview :src="scope.row.healthPathIcon" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="显示顺序" align="center" prop="orderNum" />
        <el-table-column label="健康状态" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:healthClassification:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="新增下级类别" placement="top">
              <el-button link type="primary" icon="Plus" v-if="scope.row.parentId!=0" @click="handleAdd(scope.row)" v-hasPermi="['system:healthClassification:add']"/>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:healthClassification:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改健康分类对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="healthClassificationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级类别" prop="parentId">
          <el-tree-select
                v-model="form.parentId"
                :data="deptOptions"
                :props="{ value: 'healthId', label: 'healthName', children: 'children' } as any"
                value-key="id"
                placeholder="选择上级类别"
                check-strictly
              />
        </el-form-item>
        <el-form-item label="健康名称" prop="healthName">
          <el-input v-model="form.healthName" placeholder="请输入健康名称" />
        </el-form-item>
        <el-form-item label="类别编码" prop="healthCategory">
          <el-input v-model="form.healthCategory" placeholder="请输入健康类别编码" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 添加或修改健康分类一级类别对话框 -->
     <el-dialog :title="dialogOne.title" v-model="dialogOne.visible" width="500px" append-to-body>
      <el-form ref="healthClassificationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="健康名称" prop="healthName">
          <el-input v-model="form.healthName" placeholder="请输入健康名称" />
        </el-form-item>
        <el-form-item label="类别编码" prop="healthCategory">
          <el-input v-model="form.healthCategory" placeholder="请输入健康类别编码" />
        </el-form-item>
        <el-form-item label="健康图标" prop="avatar">
          <image-upload v-model="form.healthPath" :limit="1"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelOne">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HealthClassification" lang="ts">
import { listHealthClassification, getHealthClassification, delHealthClassification, addHealthClassification, updateHealthClassification } from '@/api/system/healthClassification/index';
import { HealthClassificationVO, HealthClassificationQuery, HealthClassificationForm } from '@/api/system/healthClassification/types';
import { json } from 'stream/consumers';

interface HealthOptionsType {
  healthId: number | string;
  healthName: string;
  children: HealthOptionsType[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const healthClassificationList = ref<HealthClassificationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const isExpandAll = ref(true);
const deptOptions = ref<HealthOptionsType[]>([]);

const queryFormRef = ref<ElFormInstance>();
const healthClassificationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogOne = reactive<DialogOption>({
  visible: false,
  title: ''
});

const deptTableRef = ref<ElTableInstance>();

const initFormData: HealthClassificationForm = {
  healthId: undefined,
  parentId: undefined,
  ancestors: undefined,
  healthName: undefined,
  healthCategory: undefined,
  orderNum: undefined,
  status: undefined,
}
const data = reactive<PageData<HealthClassificationForm, HealthClassificationQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    healthName: undefined,
    params: {
    }
  },
  rules: {
    parentId: [
      { required: true, message: "父部门id不能为空", trigger: "blur" }
    ],

    healthName: [
      { required: true, message: "健康名称不能为空", trigger: "blur" }
    ],
    healthCategory: [
      { required: true, message: "健康类别编码不能为空", trigger: "blur" }
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "健康状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询健康分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listHealthClassification(queryParams.value);
  const data = proxy?.handleTree<HealthClassificationVO>(res.rows, 'healthId');
  if (data) {
    healthClassificationList.value = data;
  }
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 取消按钮 */
const cancelOne = () => {
  reset();
  dialogOne.visible = false;
}
/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(healthClassificationList.value, isExpandAll.value);
};

/** 展开/折叠所有 */
const toggleExpandAll = (data: HealthClassificationVO[], status: boolean) => {
  data.forEach((item) => {
    deptTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  healthClassificationFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HealthClassificationVO[]) => {
  ids.value = selection.map(item => item.healthId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async (row?: HealthClassificationVO) => {
  reset();
  const res = await listHealthClassification();
  const data = proxy?.handleTree<HealthOptionsType>(res.rows, 'healthId');
  if (data) {
    deptOptions.value = data;
  console.log(deptOptions)
    if (row && row.healthId) {
      form.value.parentId = row?.healthId;
    }
    dialog.visible = true;
    dialog.title = '添加健康分类';
    form.value.ancestors='0'
  }
};

/** 新增一级按钮操作 */
const handleAddOne = () => {
  reset();
  dialogOne.visible = true;
  dialogOne.title = "添加健康一级分类";
  form.value.parentId='0'
  form.value.ancestors='0'
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HealthClassificationVO) => {
  reset();
  const _healthId = row?.healthId || ids.value[0]
  const res = await getHealthClassification(_healthId);
  Object.assign(form.value, res.data);
  if(row.parentId==0){
  dialogOne.visible = true;
  dialogOne.title = "修改健康一级分类";
  }else{ 
  dialog.visible = true;
  dialog.title = "修改健康下级分类";
  }
}

/** 提交按钮 */
const submitForm = () => {
  healthClassificationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.healthId) {
        await updateHealthClassification(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addHealthClassification(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      dialogOne.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HealthClassificationVO) => {
  const _healthIds = row?.healthId || ids.value;
  await proxy?.$modal.confirm('是否确认删除健康分类编号为"' + _healthIds + '"的数据项？').finally(() => loading.value = false);
  await delHealthClassification(_healthIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/healthClassification/export', {
    ...queryParams.value
  }, `healthClassification_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
